package com.rock.securityresearch.equity

import com.rock.securityresearch.equity.HistoricalStockQuote
import com.rock.securityresearch.util.CsvUtil

import java.io.ByteArrayInputStream
import scala.util.Try

object QuotePriceCsvParser {
    def parse(data: Array[Byte], encoding: String): Try[Option[List[HistoricalStockQuote]]] = {
       Try{
           val csvData: List[List[String]] = CsvUtil.read(ByteArrayInputStream(data), encoding)
           val dataBody = csvData.tail
           if (dataBody.isEmpty) then None else Some(dataBody.map(parseHistoricalStockQuote))
       }
    }

    private def parseHistoricalStockQuote(cols: List[String]): HistoricalStockQuote = {

        HistoricalStockQuote(
            code = cols(1).substring(1),
            name = cols(2),
            date = cols(0),
            topen = cols(6).toDoubleOption,
            tclose = cols(3).toDoubleOption,
            pchg = cols(9).toDoubleOption,
            chg = cols(8).toDoubleOption,
            tcap = cols(13).toDoubleOption,
            mcap = cols(14).toDoubleOption,
            voturnover = cols(11).toDoubleOption,
            vaturnover = cols(12).toDoubleOption,
            turnover = cols(10).toDoubleOption
        )
    }
}
